<!-- 
  创 建：李书文
  日 期：2023-6-8
  描 述：入册管理
-->
<template>
  <div class='cbookAddCard' v-loading="loading">

    <div class="transferContent">
      <a-transfer :data-source="dataArr" :filter-option="filterOption" :one-way="true" :show-select-all="false"
        v-model:selected-keys="selectedKeys"
        :titles="[`${dataArr && dataArr.length ? dataArr.length:0}项未入册表卡`, `${targetKeys&&targetKeys.length ? targetKeys.length : 0}项已入册表卡 ${rightTitle.cbookNo ? '('+rightTitle.cbookNo+'-'+rightTitle.cbookName+')' :''}`]"
        :disabled="isDisable" @change="handlechange">
        <template #children="{
                    direction,// 渲染列表的方向
                    filteredItems,//过滤后的数据
                    selectedKeys,//选中的条目itemSelect
                    onItemSelectAll,//勾选一组条目
                    onItemSelect,//	勾选条目
                }">
          <div :class="direction==='right'? 'rightTable':'leftTable'">
            <div class="search">
              <div v-if="direction === 'right'" class="table-button">
                <a-button type="primary" ghost @click="sort" :disabled="rightCbookId ? false:true">快速排序</a-button>
                <a-button type="primary" ghost @click="handlechange"
                  :disabled="rightCbookId ? false:true">移出表册</a-button>
              </div>
            </div>
            <div class="left" v-if="direction=='left'">
              <WrsTable :scroll="{x:1000}" :showSelection="false" :serialWidth="60"
                :rowSelection="getRowSelectionLeft ({selectedKeys,onItemSelectAll, onItemSelect,direction})"
                :columns="leftTableColumns" :dataSource="filteredItems" @change="filterChange" rowKey="cardId">
                <template #editSlot="{ column, text,record}">
                  <template v-if="column.dataIndex == 'cardNo'">
                    <span>{{text}}</span>
                    <a-tag color="blue" v-if="record.cardType == '1'">分表</a-tag>
                    <a-tag color="green" v-if="record.cardType == '2'">总表</a-tag>
                  </template>
                </template>
              </WrsTable>
            </div>
            <div class="right" v-else>
              <WrsTable :rowSelection="getRowSelectionRight ({selectedKeys,onItemSelectAll, onItemSelect,direction})"
                :columns="leftTableColumns" :dataSource="targetKeys" :scroll="{x:800}" @change="rightFilterChange"
                rowKey="cardId">
                <template #editSlot="{ column, text,record}">
                  <template v-if="column.dataIndex == 'cardNo'">
                    <span>{{text}}</span>
                    <a-tag color="blue" v-if="record.cardType == '1'">分表</a-tag>
                    <a-tag color="green" v-if="record.cardType == '2'">总表</a-tag>
                  </template>
                </template>
              </WrsTable>
            </div>

          </div>
        </template>
      </a-transfer>
    </div>
  </div>
</template>

<script setup>
import WrsTable from '@/components/WrsTable/index.vue'
import { reactive, h, ref, onMounted, nextTick, watch } from "vue";

let rightCbookId = ref('01111');
let form = ref({
  sortType: '1',
  serial: '',
  cardIdList: []
})
let rightTitle = reactive({
  cbookNo: '1002',
  cbookName: 'qwer',
})

let loading = ref(false);

const leftTableColumns = [
  {
    dataIndex: 'customerNo',
    title: '客户编号',
    width: 130,
  },
  {
    dataIndex: 'cardNo',
    title: '表卡编号',
    width: 210,
  }]

const dataArr = ref([
  {
    customerNo: 1111,
    cardId: 1,
    cardType: 1,//fen
    cardNo: 123123,
    masterCardNo: ""

  },
  {
    customerNo: 1111,
    cardId: 4,
    cardType: 2,//fen
    cardNo: 345678,
    masterCardNo: ""

  },
  {
    customerNo: 222,
    cardId: 2,
    cardType: 2,
    cardNo: 12345,
    masterCardNo: "123123"
  },
  {
    customerNo: 3333,
    cardId: 3,
    cardType: 2,
    cardNo: 234234,
    masterCardNo: ""
  }
]);//左侧
const targetKeys = ref([]);  //右侧表格数据源
let leftData = ref([]);
let selectArr = ref([]);
let rightSelectArr = ref([]);
let isDisable = ref(false);
// watch(
//   () => targetKeys.value,
//   (newValue) => {
//     if (!newValue || newValue.length == 0) {
//       isDisable.value = true;

//       setTimeout(() => {
//         leftData.value = [...dataArr.value];
//       }, 500)

//     } else {
//       isDisable.value = false;
//     }

//   },
//   {
//     immediate: true,
//     deep: true
//   }
// )
watch(
  () => selectArr.value,
  (newVal) => {
    if (newVal.length > 0 && rightCbookId.value) {
      isDisable.value = false;
    }
  },
  {
    immediate: true,
    deep: true
  }
)
watch(
  () => rightSelectArr.value,
  (newVal) => {
    console.log('监听右边选中列', rightCbookId.value)
    if (newVal.length > 0 && rightCbookId.value) {
      isDisable.value = false;
    }
  },
  {
    immediate: true,
    deep: true
  }
)
const filterOption = (inputValue, option) => {
  return option.description.indexOf(inputValue) > -1
}
const selectedRowKeysLeft = ref([]);
const getRowSelectionLeft = ({ disabled, selectedKeys, onItemSelectAll, onItemSelect }) => {
  return {
    selectedRowKeys: selectedRowKeysLeft.value,
    onchange(selectedRowKeys, selectedRows) {
      selectedRowKeysLeft.value = selectedRowKeys
    },
    // getCheckboxProps: (item) => ({
    //   disabled: rightCbookId.value && (selectArr.value != item.areaId) ? true : !rightCbookId.value ? false : false,
    // }),
    onSelectAll(selected, selectedRows) {
      selectedRows = selectedRows.filter(item => item)
      const treeSelectedKeys = selectedRows.map(({ key }) => key);
      onItemSelectAll(treeSelectedKeys, selected);
      selectArr.value = treeSelectedKeys;
      form.value.leftCardIds = selectedRows.map(item => item.cardId);
      selectedKeys = treeSelectedKeys?.map(item => +item)
      dataArr.value.filter(item => {
        if (selected) {
          selectedRowKeysLeft.value.push(item.cardId)
        } else {
          selectedRowKeysLeft.value = []
        }
      })

    },
    onSelect(record, selected) {
      console.log(record, selected)
      // 勾选no相同的
      let array = dataArr.value.filter(item => item.customerNo == record.customerNo)
      if (array.length) {
        array.forEach(item => {
          autoSelect(item, selected, dataArr.value, selectedRowKeysLeft.value, 'left')
        })
      } else {
        autoSelect(record, selected, dataArr.value, selectedRowKeysLeft.value, 'left')
      }

      let arr = []
      selectedRowKeysLeft.value.forEach(item => {
        dataArr.value.forEach(v => {
          if (v.cardId == item) {
            arr.push(v)
          }
        })
      })
      selectArr.value = arr;
      console.log(record.cardId)
      onItemSelect(record.cardId.toString(), selected);
    }
  }
}

const selectedRowKeysRight = ref([]);
const autoSelect = (record, selected, data = [], selectedRowKeys = [], type) => {
  console.log('处理数据：', record, selected, data, selectedRowKeys, type)
  let list = [record.cardId]
  // 获取所有需要同步修改的子节点
  if (record.cardType === 2) {//总表
    data.forEach(item => {
      if (item.masterCardNo === record.cardNo) {
        list.push(item.cardId)
      }
    })
  }
  if (selected) {
    // 根据子选父
    if (record.cardType === 1) {
      // 查询父级节点
      const a = data.find(item => item.cardNo == record.masterCardNo);
      // 查询所有同级子节点（不包含自生）
      const b = data.filter(item => item.masterCardNo == record.masterCardNo && item.cardNo != record.cardNo).map(item => item.cardId);
      if (a) {
        list.push(a.cardId)
      }

      if (b) {
        b.forEach(item => {
          list.push(item)
        })
      }
    }
    selectedRowKeys.push(...list)
  } else {
    if (record.cardType === 1) {
      // 查询所有同级子节点（不包含自生）
      const a = data.filter(item => item.masterCardNo == record.masterCardNo && item.cardNo != record.cardNo).map(item => item.cardId);
      //   查询选中节点的父级cardId
      const pCardId = data.filter(item => item.cardNo == record.masterCardNo)[0]?.cardId
      console.log("同级子节点a: ", a, "pCardId", pCardId)
      // 判断同级子节点是否存在选中
      const b = selectedRowKeys.filter(item => a.includes(item));
      console.log(b)
      if (b.length !== 0) {
        b.forEach(item => {
          list.push(item)
        })
      }
      // 将父节点添加到删除列表
      list.push(pCardId)
      console.log('将要删除的：', list)
    }
    selectedRowKeys = selectedRowKeys.filter(item => !list.includes(item)); // 删除所有值为3的元素
  }
  if (type == "right") {
    selectedRowKeysRight.value = selectedRowKeys
  } else if (type == 'left') {
    selectedRowKeysLeft.value = selectedRowKeys
    console.log("selectedRowKeysLeft", selectedRowKeysLeft.value)
  }
}
const getRowSelectionRight = ({ selectedKeys, onItemSelectAll, onItemSelect }) => {
  return {
    selectedRowKeys: selectedRowKeysRight.value,
    onchange(selectedRowKeys, selectedRows) {
      selectedRowKeysRight.value = selectedRowKeys
    },
    onSelectAll(selected, selectedRows) {
      const treeSelectedKeys = selectedRows.map(({ key }) => key);
      onItemSelectAll(treeSelectedKeys, selected);
      form.value.cardIdList = selectedRows.map(item => item.cardId);
      rightSelectArr.value = selectedRows;
      let array = targetKeys.value.filter(item => item)
      array.forEach(item => {
        autoSelect(item, selected, targetKeys.value, selectedRowKeysRight.value, 'right')
      })
    },
    onSelect(record, selected) {
      // 勾选no相同的
      let array = targetKeys.value.filter(item => item.customerNo == record.customerNo)
      array.forEach(item => {
        autoSelect(item, selected, targetKeys.value, selectedRowKeysRight.value, 'right')
      })
      onItemSelect(record.key.toString(), selected);
      let arr = []
      selectedRowKeysRight.value.forEach(item => {
        targetKeys.value.forEach(v => {
          if (v.key == item) {
            arr.push(v)
          }
        })
      })
      rightSelectArr.value = arr;
      form.value.cardIdList = selectedRowKeysRight.value;
    }
  }
}

const filterChange = (page, filters, sorter) => {
}
const rightFilterChange = (page, filters, sorter) => {
}
const handlechange = (list, direction, moveKeys) => {

  if (direction == 'right') {
    console.log("穿梭事件:", "dataArr:", dataArr.value, "direction-方向：", direction, "moveKeys-选中条的id：", selectedRowKeysLeft.value)
    console.log('targetKeys', targetKeys.value);
    targetKeys.value.push(...dataArr.value.filter(item => selectedRowKeysLeft.value.includes(item.cardId)));
    dataArr.value = dataArr.value.filter(item => !selectedRowKeysLeft.value.includes(item.cardId))
    console.log('----end----');
    console.log("穿梭事件:", "dataArr:", dataArr.value, "direction-方向：", direction, "targetKeys：", targetKeys.value)
    // 往右边传数据
    // newRightList.value = list;
    nextTick(() => {
      let newElement = document.querySelectorAll('.rightTable .ant-table-row');
      targetKeys.value.forEach((v, i) => {
        if (!v.old) {
          newElement.forEach(item => {
            if (item.getAttribute('data-row-key') == +v.key) {
              item.style.background = '#ECEFFE';
              let rightSelected = item.querySelectorAll('.ant-table-cell-fix-left');
              rightSelected.forEach(p => {
                p.style.background = '#ECEFFE';
              })
            }
          })
        }
      });
    })
  } else {
    // 往左边传数据
    let isOld = [];
    // 判断是否有已经入册的数据
    targetKeys.value.forEach(item => {
      selectedRowKeysRight.value.forEach(v => {
        if (item.cardId == v && item.old) {
          isOld.push(item)
        }
      })
    })
    if (isOld.length > 0) {
      alert('只能移出新入册的表卡')
    } else {
      // 添加到左侧数据
      dataArr.value.push(...targetKeys.value.filter(item => selectedRowKeysRight.value.includes(item.cardId)));
      // 删除右侧移除的数据
      targetKeys.value = targetKeys.value.filter(item => !selectedRowKeysRight.value.includes(item.cardId))


    }
    console.log('右边剩余的数据：', targetKeys.value)
    selectedRowKeysRight.value = [];
  }
}
watch(() => rightCbookId.value,
  () => {
    console.log("12345566")
    selectedRowKeysRight.value = []
  }
)

</script>

<style lang='less' scoped>
.cbookAddCard {
  height: 100%;

  .company {
    height: 74px;
    border-bottom: 1px solid #eee;
    padding: 20px;
  }

  .transferContent {
    height: calc(100% - 140px);
    border: 1px solid #eee;
    position: relative;

    .ant-transfer {
      height: 100%;

      :deep(.ant-transfer-list-body) {
        padding: 0px 10px;
      }

      :deep(.ant-transfer-list) {
        width: 46%;
        background: #fff;
        border: none;
      }

      :deep(.ant-transfer-list:nth-of-type(1)) {
        border-right: 1px solid #d9d9d9;
      }

      :deep(.ant-transfer-list:nth-of-type(3)) {
        border-left: 1px solid #d9d9d9;
      }

      :deep(.ant-transfer-list-header) {
        height: 45px;
        line-height: 45px;
      }

      :deep(.ant-transfer-list-body-customize-wrapper) {
        height: 100%;
      }
    }

    :deep(.ant-empty) {
      line-height: 340px;
    }

    :deep(.ant-transfer-list-header-selected) {
      span:nth-child(1) {
        display: none;

      }

      span:nth-child(2) {
        font-weight: 600;
      }
    }

    .search {
      margin: 10px 0px;

      .table-button>button {
        margin-right: 10px;
      }
    }

    .left {
      height: calc(100% - 20px);
    }

    :deep(.leftTable) {
      height: 100%;
    }

    :deep(.leftTable .ant-table-body) {
      tr {
        height: 50px;
      }
    }

    .right {
      height: calc(100% - 52px);
    }

    :deep(.rightTable .ant-table-body) {
      tr {
        height: 50px;
      }
    }

    :deep(.one-td) {
      position: relative;
    }

    :deep(.sortable-chosen) {
      cursor: move !important;
    }

    :deep(.ant-table-cell > .ant-form-item) {
      margin: 0px;
    }

    :deep(.paddingLeft) {
      padding-left: 32px;
    }

    :deep(.drag) {
      height: 30px !important;
      overflow: hidden !important;
      background: #fff !important;
      opacity: 1 !important;
      border-radius: 10px;
      box-shadow: 0 0 4px 2px #ccc;
      padding: 10px 20px;
      display: flex;
      justify-content: center;
      align-items: center;

      .ant-table-cell:first-child {
        display: block;
        padding: 0 20px !important;
        height: 30px !important;
        line-height: 30px;
        width: 100px !important;
        background: #fff !important;
        position: relative;
      }
    }

    :deep(.dragged-item) {
      opacity: 1 !important;
    }

    :deep(.ant-table-thead tr) {
      height: 50px;
    }

    .ant-table-wrapper {
      height: 100%;

      :deep(.ant-checkbox-wrapper) {
        margin: 10px 0px;
      }
    }

    :deep(.rightTable) {
      height: calc(100% - 10px);

      .ant-table-selection-column {
        width: 90px
      }

      :deep(.serialNum) {
        margin-left: 20px;
      }
    }

    :deep(.ant-table-filter-column) {
      justify-content: flex-start;
    }

    :deep(.ant-table-column-sorters) {
      flex: unset;
      justify-content: flex-start;
    }

    :deep(.ant-table-column-title) {
      flex: inherit;
    }

    :deep(.ant-table-tbody) {
      .ant-table-row:hover>td {
        background: #ECEFFE !important;
      }

      .ant-table-cell-row-hover {
        background: #ECEFFE;
      }

      .ant-table-row-selected>td {
        background: none;
      }
    }
  }

  .cbookAddCard-btn {
    position: absolute;
    right: 30px;
    top: 206px;
    z-index: 100;
  }

  .submit-btn {
    height: 70px;
    padding: 20px 40px 20px 0px;
    display: flex;
    flex-direction: row-reverse;
  }

  .otherSearch {
    border-top: 1px solid transparent;
    margin-right: 20px;
    position: relative;

    :deep(.ant-select-selector) {
      padding-left: 60px;
    }

    .otherSearch-text {
      position: absolute;
      z-index: 1;
      left: 16px;
      bottom: 6px;
    }

    .ant-select-selector {
      height: 34px;
    }

    :deep(.ant-select-selection-search-input) {
      padding-left: 48px !important;
    }
  }
}
</style>